<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础" name="info">
        <InfoForm
          ref="infoRef"
          v-model="formData"
          v-model:activeName="activeName"
          :is-detail="isDetail"
        />
      </el-tab-pane>
      <el-tab-pane label="价格" name="sku">
        <SkuForm
          ref="skuRef"
          v-model="formData"
          v-model:activeName="activeName"
          :is-detail="isDetail"
        />
      </el-tab-pane>
      <el-tab-pane label="详情" name="description">
        <DescriptionForm
          ref="descriptionRef"
          v-model="formData"
          v-model:activeName="activeName"
          :is-detail="isDetail"
        />
      </el-tab-pane>
      <el-tab-pane label="其它" name="other">
        <OtherForm
          ref="otherRef"
          v-model="formData"
          v-model:activeName="activeName"
          :is-detail="isDetail"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'
import InfoForm from './InfoForm.vue'
import DescriptionForm from './DescriptionForm.vue'
import OtherForm from './OtherForm.vue'
import SkuForm from './SkuForm.vue'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'
import type { Spu } from '@/api/mall/product/spu'
import { useShopStore } from '@/store/modules/shop'

defineOptions({ name: 'ProductSpuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const infoRef = ref() // 产品信息 Ref
const skuRef = ref() // 产品规格 Ref
const descriptionRef = ref() // 产品详情 Ref
const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<Spu>({
  shopId: undefined, // 店铺编号
  name: '', // 产品名称
  type: undefined, // 产品类型
  platformCategoryId: undefined, // 行业类目
  categoryId: undefined, // 产品分类
  keyword: '', // 关键字
  introduction: '', // 产品简介
  status: 1, // 状态
  unitName: '件', // 计价单位
  unitValue: 1, // 计价数值
  stepQuantity: 1, // 计价数值，即每次加购数量
  picUrl: '', // 产品封面图
  sliderPicUrls: [], // 产品轮播图
  deliveryTypes: [0], // 配送方式数组
  deliveryTemplateId: undefined, // 运费模版
  brandId: undefined, // 产品品牌
  specType: false, // 是否多规格
  isBrokerage: false, // 是否支持分佣
  isIntegral: false, //是否支持积分抵扣
  giveIntegral: 0, //赠送积分
  skus: [],
  description: '', // 产品详情
  recommend: 0, //推荐类型
  isSticky: false, //是否置顶
  sort: 1, // 展示顺序
  virtualSalesCount: 0, // 虚拟销量
  limitMinQuantity: 1, // 起购数量
  limitMaxQuantity: 999, // 限购数量
  priceMode: 1, // 计价模式
  dishAttribute: 0 // 菜肴属性
})

/** 获得详情 */
const getDetail = async () => {
  if ('ProductSpuDetail' === name) {
    isDetail.value = true
  }
  const id = params.id as unknown as number
  if (!id) {
    return
  }
  formLoading.value = true
  try {
    const res = (await ProductSpuApi.getSpu(id)) as ProductSpuApi.Spu
    res.skus?.forEach((item) => {
      item.weight = item.weight * 1000
      if (isDetail.value) {
        item.price = floatToFixed2(item.price)
        item.marketPrice = floatToFixed2(item.marketPrice)
        item.wholesalePrice = floatToFixed2(item.wholesalePrice)
        item.vipPrice = floatToFixed2(item.vipPrice)
        item.costPrice = floatToFixed2(item.costPrice)
        item.firstBrokeragePrice = floatToFixed2(item.firstBrokeragePrice)
        item.secondBrokeragePrice = floatToFixed2(item.secondBrokeragePrice)
      } else {
        // 回显价格分转元
        item.price = formatToFraction(item.price)
        item.marketPrice = formatToFraction(item.marketPrice)
        item.wholesalePrice = formatToFraction(item.wholesalePrice)
        item.vipPrice = formatToFraction(item.vipPrice)
        item.costPrice = formatToFraction(item.costPrice)
        item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice)
        item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice)
      }
    })
    formData.value = res
  } finally {
    formLoading.value = false
  }
}

/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单
    await unref(infoRef)?.validate()
    await unref(skuRef)?.validate()
    await unref(descriptionRef)?.validate()
    await unref(otherRef)?.validate()
    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value)) as ProductSpuApi.Spu
    deepCopyFormData.skus!.forEach((item) => {
      item.weight = item.weight / 1000
      // 给sku name赋值
      item.name = deepCopyFormData.name
      // sku相关价格元转分
      item.price = convertToInteger(item.price)
      item.marketPrice = convertToInteger(item.marketPrice)
      item.wholesalePrice = convertToInteger(item.wholesalePrice)
      item.vipPrice = convertToInteger(item.vipPrice)
      item.costPrice = convertToInteger(item.costPrice)
      item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice)
      item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice)
    })
    // 处理轮播图列表
    const newSliderPicUrls: any[] = []
    deepCopyFormData.sliderPicUrls?.forEach((item: any) => {
      // 如果是前端选的图
      typeof item === 'object' ? newSliderPicUrls.push(item.url) : newSliderPicUrls.push(item)
    })
    deepCopyFormData.sliderPicUrls = newSliderPicUrls
    // 校验都通过后提交表单
    const data = deepCopyFormData as ProductSpuApi.Spu
    const id = params.id as unknown as number
    if (!id) {
      await ProductSpuApi.createSpu(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductSpuApi.updateSpu(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductSpu' })
}

/** 初始化 */
const shopStore = useShopStore()
onMounted(async () => {
  await getDetail()
  if (!formData.value!.type) {
    await shopStore.setCategoryInfoAction()
    const categoryInfo = shopStore.categoryInfo
    formData.value!.type = categoryInfo.code
  }
})
</script>
